package com.tomato.controller;

import com.tomato.dto.Result;
import com.tomato.dto.UserUpdateDTO;
import com.tomato.entity.User;
import com.tomato.service.UserService;
import com.tomato.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Slf4j
@RestController
@RequestMapping("/user")
@Tag(name = "用户信息", description = "用户信息管理接口")
public class UserController {
    private final UserService userService;
    private final String uploadDir = "avatars/";
    private final JwtUtil jwtUtil; // 注入JwtUtil

    public UserController(UserService userService, JwtUtil jwtUtil) {
        this.userService = userService;
        this.jwtUtil = jwtUtil;
        // 确保上传目录存在
        try {
            Files.createDirectories(Paths.get(uploadDir));
        } catch (IOException e) {
            log.error("Failed to create upload directory", e);
        }
    }

    @Operation(summary = "获取当前用户信息")
    @GetMapping("/profile")
    public Result<User> getProfile(@RequestHeader("Authorization") String token, HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromToken(token.replace("Bearer ", ""));
        log.debug("Get profile request for user: {}", userId);
        User user = userService.getCurrentUser(userId);
        // 移除头像路径字段，因为有专门的头像接口处理
        user.setAvatarPath(null);
        return Result.success(user);
    }

    @Operation(summary = "更新用户信息, 请勿使用该接口进行修改头像")
    @PutMapping("/profile")
    public Result<Void> updateProfile(
            @RequestHeader("Authorization") String token,
            @RequestBody UserUpdateDTO updateDTO) {
        Long userId = jwtUtil.getUserIdFromToken(token.replace("Bearer ", ""));
        log.debug("Update profile request for user: {}", userId);
        userService.updateUser(userId, updateDTO);
        return Result.success();
    }

    @Operation(summary = "上传用户头像")
    @PostMapping(value = "/avatar", consumes = "multipart/form-data")
    public Result<String> uploadAvatar(
            @RequestHeader("Authorization") String token,
            @RequestParam("file") MultipartFile file) {
        Long userId = jwtUtil.getUserIdFromToken(token.replace("Bearer ", ""));
        log.debug("Upload avatar request for user: {}", userId);

        if (file.isEmpty()) {
            throw new RuntimeException("请选择要上传的文件");
        }

        // 限制文件大小不超过5MB
        if (file.getSize() > 5 * 1024 * 1024) {
            throw new RuntimeException("文件大小不能超过5MB");
        }

        try {
            // 读取图片并转换为JPG格式
            BufferedImage originalImage = ImageIO.read(file.getInputStream());
            if (originalImage == null) {
                throw new RuntimeException("无效的图片文件");
            }

            // 创建新的JPG图片
            BufferedImage jpgImage = new BufferedImage(
                    originalImage.getWidth(),
                    originalImage.getHeight(),
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = jpgImage.createGraphics();
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, originalImage.getWidth(), originalImage.getHeight());
            g.drawImage(originalImage, 0, 0, null);
            g.dispose();

            // 转换为JPG字节流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(jpgImage, "jpg", baos);
            byte[] jpgBytes = baos.toByteArray();

            // 使用用户ID作为文件名
            String newFilename = userId + ".jpg";

            // 保存文件
            Path path = Paths.get(uploadDir + newFilename);
            Files.copy(new ByteArrayInputStream(jpgBytes), path, StandardCopyOption.REPLACE_EXISTING);

            // 更新用户头像路径
            String relativePath = "avatars/" + newFilename;
            String avatarPath = userService.uploadAvatar(userId, relativePath);

            return Result.success(avatarPath);
        } catch (IOException e) {
            log.error("Failed to upload avatar", e);
            throw new RuntimeException("上传头像失败");
        }
    }

    @Operation(summary = "获取用户头像")
    @GetMapping(value = "/avatar/{userId}", produces = "image/jpeg")
    public byte[] getAvatar(@PathVariable Long userId) {
        try {
            User user = userService.getCurrentUser(userId);
            String avatarPath = user.getAvatarPath();
            Path path = Paths.get(avatarPath);
            return Files.readAllBytes(path);
        } catch (Exception e) {
            log.error("Failed to read avatar for user: {}", userId, e);
            try {
                // 返回默认头像
                Path defaultAvatarPath = Paths.get("avatars/default.png");
                if (Files.exists(defaultAvatarPath)) {
                    return Files.readAllBytes(defaultAvatarPath);
                } else {
                    return new byte[0];
                }
            } catch (IOException ioException) {
                log.error("Failed to read default avatar", ioException);
                return new byte[0];
            }
        }
    }
}